#include <iostream>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

int main(int argc, char const *argv[]) {
  int client_fd;
  struct sockaddr_in server_addr;
  char buffer[1024] = {0};
  const char *message = "Hello, server!";
  const char *server_ip = "127.0.0.1";
  const int PORT = 11111;

  if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    std::cerr << "Failed to create socket." <<std::endl;
    return 1;
  }
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(PORT);

  if (inet_pton(AF_INET, server_ip, &server_addr.sin_addr) <= 0) {
    std::cerr << "Invalid address or address not supported." << std::endl;
    return 1;
  }
  if(connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0 ) {
    std::cerr << "Failed to connect to server." << std::endl;
    return 1;
  }
  std::cout << "Connected to server " << server_ip << ":" << PORT << std::endl;
  while (true) {
    char message[1024];
    cout << "Please input message: ";
    cin.getline(message, 1024);
    if (strlen(message) > 0) {
      int send_len = send(client_fd, message, strlen(message), 0);
      if (send_len == -1) {
        cerr << "Failed to send message." << endl;
        close(client_fd);
        return -1;
      } else {
        std::cout << "Send message: " << message << std::endl;
      }
    }
    char buffer[1024];
    int recv_len = recv(client_fd, buffer, 1024, 0);
    if (recv_len == -1) {
      cerr << "Failed to receive message." << endl;
      close(client_fd);
      return -1;
    } else if (recv_len == 0) {
      cout << "Server closed connection." << endl;
      close(client_fd);
      return 0;
    } else {
      buffer[recv_len] = '\0';
      cout << "received message: " << buffer << endl;
    }
  }
  close(client_fd);
  return 0;
}
